from rest_framework import viewsets
from app01 import models
from django.http import JsonResponse
from rest_framework import status
from app01.utils.serializers.Student_ser import StudentSerializer_list,StudentSerializer_show,StudentBehaviorSerializer
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from app01.utils.form.Student import * 
from datetime import datetime
from django.views.decorators.csrf import csrf_exempt
from app01.models import Student
import json
class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer_list
    def list(self, request, *args, **kwargs):
        user_id = request.session.get("user_id")
        psychologist = models.Psychologist.objects.get(psychologist_id=user_id)
        queryset = psychologist.students_as_head_teacher.all()
        serializer = StudentSerializer_list(queryset, many=True)
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        print(data)
        return Response(data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = {
            "data": serializer.data,
            "status": True  # 根据需要设置这个字段的值
        }
        return Response(data)
class StudentViewSet_classname(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer_list
    def list(self, request, *args, **kwargs):
        # class_name = request.GET.get("classname")
        print(request.GET.get("classname"))

        # print(request.query_params) # 获取请求体数据
        # class_name = json.loads(request.body)
        # print(1)
        # print(class_name)
        Class = models.Classroom.objects.get(class_name = request.GET.get("classname"))
        queryset = Class.class_stu.all()
        serializer = self.get_serializer(queryset, many=True)
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        return Response(data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        return Response(data)
class StudentViewSet_Psychologist_add(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer_list

    def list(self, request, *args, **kwargs):
        user_id = request.session.get("user_id")
        psychologist = models.Psychologist.objects.get(psychologist_id=user_id)
        queryset = psychologist.students_as_head_teacher.all()
        serializer = self.get_serializer(queryset, many=True)
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        return Response(data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        return Response(data)
class Student_show(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer_show     #使用序列化器去查询对象

    def list(self, request, *args, **kwargs):
        # 从请求的GET参数中获取学生ID
        stu_id = request.GET.get('stu_id')
        # 根据学生ID查询学生对象
        stu = models.Student.objects.get(student_id=stu_id)
         # 设置查询集为单个学生对象
        queryset = stu
        # 使用序列化器处理查询集，以便以合适的格式返回数据
        serializer = StudentSerializer_show(queryset)
        # 构建返回的数据字典，包含序列化后的数据和状态信息
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        # 返回构建好的数据
        return Response(data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        return Response(data)
@csrf_exempt
def Student_add(request):
    if request.method == "POST":
        data = json.loads(request.body)
        form = StuModel_add_ModelForm(data=data['data'])  # 使用自定义的表单类处理数据
        if form.is_valid():
            # 保存学生对象
            student = form.save()
            
            return JsonResponse({'status': True, 'student_id': student.student_id})
        else:
            # 如果表单验证失败，返回错误信息
            errors = form.errors
            return JsonResponse({'status': False, 'errors': errors}, status=400)
    
    # 如果不是 POST 请求，返回错误信息
    return JsonResponse({'status': False, 'errors': '仅支持POST请求'}, status=405)
class StudentBehaviorAPIView(APIView):
    def post(self, request, *args, **kwargs):
        data = request.data
        student_id = data['data'].get('stu_id')
        emotion = data['data'].get('emotion')
        behavior = data['data'].get('behavior')
        
        # 获取当前时间
        current_time = datetime.now()
        
        try:
            student = Student.objects.get(student_id=student_id)
        except Student.DoesNotExist:
            return Response({"message": "学生不存在"}, status=status.HTTP_404_NOT_FOUND)

        # 获取之前的情绪和行为信息，如果为 None 则初始化为空字典
        emotion_and_behavior = student.emotion_and_behavior if student.emotion_and_behavior else {}

        # 更新情绪和行为信息
        emotion_and_behavior[str(current_time)] = {'emotion': emotion, 'behavior': behavior}

        # 更新学生对象的情绪和行为信息字段
        student.emotion_and_behavior = emotion_and_behavior
        student.save()

        # 使用序列化器返回响应
        serializer = StudentBehaviorSerializer(student)
        return JsonResponse({'status': True, 'message': '添加成功'})
import os
import erniebot
@csrf_exempt
def Student_bug_model(request):
    if request.method == "GET":
        erniebot.api_type = "aistudio"
        erniebot.access_token = "c9e21a30789fdab0dacae97eca3b9838be10706b"
        #SYSTEM_MESSAGE = "你的任务是执行以下操作：1-  给定你需要改卷子的学科2-  给定你题目的划分规则3 - 给定你批改卷子的规则(如果没有给你改卷标准的话但是会给你总分,你只用到最后给我输出一个json文件，其他什么都不要有，正确的话请给出那一题的得分(用数字，全对的话，不要用满分)，)3 - 对标准答案进行语义理解与考生的作答进行语义理解4 - 给出你认为考生每一道题应该给的分数以及错因5 - 输出一个 json 对象，其中包含以下键：title、score，Cause of error，其他内容不要有(只用给出json文件就可以了)。使用以下格式：改卷学科： {discipline}改卷规则： {rules}标准答案： {standard}考生作答： {student}输出 JSON：<包含第几道题目和那一题的分数，以及这道题目的错因>"
        SYSTEM_MESSAGE = "你是一个经验丰富的心理辅导老师"
        prompt = request.GET.get('message')
        print(prompt)
        response = erniebot.ChatCompletion.create(
        model="ernie-4.0",
        system=SYSTEM_MESSAGE,
        messages=[
             {"role": "user", "content": prompt}
        ]
        )
        res = response.get('result')
        print(res)

        return JsonResponse({'status': True, 'message': res})
    